import 'package:flutter/material.dart';
import 'package:flutter_public/flutter_public.dart';

import 'notifier/test_main_notifier.dart';
import 'test_detail_page.dart';
import 'test_list_page.dart';

/// FileName test_main_page
///
/// @Author lax
/// @Date 2024/6/12
///
/// @Description

class TestMainPage extends StatefulWidget {
  final int? initialIndex;

  const TestMainPage({super.key, this.initialIndex});

  @override
  State<StatefulWidget> createState() {
    return _TestMainPageState();
  }
}

class _TestMainPageState extends State<TestMainPage>
    with TickerProviderStateMixin {
  late TestMainNotifier _notifier;

  @override
  void initState() {
    super.initState();
    _notifier =
        TestMainNotifier(provider: this, initialIndex: widget.initialIndex);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PublicAppBar(
        title: '首页',
        actions: [allButton()],
      ),
      body: body(),
      floatingActionButton: FloatingActionButton(
        child: const Icon(Icons.add),
        onPressed: () {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return const TestDetailPage();
          })).then((value) {
            if (value != null) {
              GlobalKey<TestListPageState>? key =
                  _notifier.currentTabModel?.key;
              key?.currentState?.refreshData();
            }
          });
        },
      ),
    );
  }

  Widget allButton() {
    return TextButton(
      onPressed: () {
        Navigator.push(context, MaterialPageRoute(builder: (_) {
          return const TestListPage();
        }));
      },
      child: const Text(
        '全部',
        style: TextStyle(color: Colors.white),
      ),
    );
  }

  Widget body() {
    return Column(
      children: [
        Container(
          color: Colors.white,
          child: PublicTabBar(
            controller: _notifier.controller,
            tabs: _notifier.dataSource.map((e) {
              return Tab(text: e.title);
            }).toList(),
          ),
        ),
        Expanded(
          child: TabBarView(
            controller: _notifier.controller,
            children: _notifier.dataSource
                .map((e) => KeepAliveWrapper(
                      child: TestListPage(
                        showAppBar: false,
                        key: e.key,
                      ),
                    ))
                .toList(),
          ),
        ),
      ],
    );
  }
}
